﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;

public partial class admin_Banners : System.Web.UI.Page
{
    private Action action = Action.UPDATE;
    private enum Action
    {
        UPDATE,
        DELETE
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
        }
        Utilities.SetLabel(Master, "Banners");
    }

    private void LoadData()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllBanners()", conn))
            {
                SqlDataReader dr = null;
                dr = cmd.ExecuteReader();
                if (dr != null)
                {
                    if (dr.HasRows)
                    {
                        gvBanners.DataSource = dr;
                        gvBanners.DataBind();
                    }
                }
                dr.Close();
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //try to upload the image
        
        string ext = fpBanner.FileName.Substring(fpBanner.FileName.Length - 4, 4);
        if (fpBanner.FileName != "" && fpBanner.FileName != null &&
                (fpBanner.HasFile == false || fpBanner.PostedFile == null ||
                (ext != ".jpg" &&
                ext != ".gif" &&
                ext != ".png" &&
                ext != ".jpeg")))
        {
            Session["message"] += " Please insert valid photo image file of type: '.jpg', '.jpeg', '.gif', '.png'<br />";
            Session["message_type_css"] = "par_message_error";
        }
        else
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand("SP_InsBanner", conn))
                    {
                        SqlParameter[] pars = new SqlParameter[5];
                        pars[0] = new SqlParameter("link", tbName.Text);
                        pars[1] = new SqlParameter("position", rbRight.Checked);
                        pars[2] = new SqlParameter("filename", fpBanner.FileName);
                        pars[3] = new SqlParameter("isActive", cbActive.Checked);
                        if(tbOrder.Text != "")
                            pars[4] = new SqlParameter("order", tbOrder.Text);
                        else pars[4] = new SqlParameter("order", 1);
                        cmd.CommandType = System.Data.CommandType.StoredProcedure;
                        foreach (SqlParameter s in pars)
                            cmd.Parameters.Add(s);
                        object val = cmd.ExecuteScalar();
                        cmd.Parameters.Clear();

                        //Stream st_item = CodeFactory.resizeImageRatio(fu_item.PostedFile.InputStream, 500, 500, fu_item.PostedFile.ContentType);
                        string pathItem = "~/images/banners/" + val + "_" + fpBanner.FileName;
                        Stream st_item = fpBanner.PostedFile.InputStream;
                        int st_item_size = (int)st_item.Length;
                        FileStream fs_item = new FileStream(Server.MapPath(pathItem), FileMode.Create, FileAccess.Write);
                        byte[] arr_item = new byte[st_item_size];
                        st_item.Read(arr_item, 0, st_item_size);
                        fs_item.Write(arr_item, 0, st_item_size);
                        fs_item.Close();
                        Session["message"] = " Insert was succesfull<br />";
                        Session["message_type_css"] = "par_message_ok";
                    }
                }
            }
            catch (Exception ex)
            {
                Session["message"] += " There was an error inserting a new banner "+ex.ToString()+"<br />";
                Session["message_type_css"] = "par_message_error";
            }
            Response.Redirect(Request.Url.ToString());
        }
    }
    protected void gvBanners_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string imgLink = "";
            CheckBox c = (CheckBox)e.Row.Cells[2].Controls[0];
            c.Attributes.Remove("disabled");
            c.Enabled = true;
            //Button btn = (Button)e.Row.FindControl("btnUpdate");
            HiddenField hf = (HiddenField)e.Row.FindControl("hfId");
            //btn.Attributes.Add("_id", hf.Value);
            imgLink += hf.Value+"_";
            hf = (HiddenField)e.Row.FindControl("hfFilename");
            //btn.Attributes.Add("filename", hf.Value);
            //btn.Attributes.Add("isActive", ((CheckBox)e.Row.Cells[2].Controls[0]).Checked.ToString());
            imgLink += hf.Value;
            Image img_galleryItem = (Image)e.Row.FindControl("imgBanner");
            if (img_galleryItem != null)
            {
                img_galleryItem.ImageUrl = "../images/banners/" + imgLink;
                img_galleryItem.Width = Unit.Pixel(300);
                img_galleryItem.Height = Unit.Pixel(300);
            }

            hf = (HiddenField)e.Row.FindControl("hfLink");
            TextBox tb = (TextBox)e.Row.FindControl("tbLink");
            tb.Text = hf.Value;
            //btn.Attributes.Add("hfLink", hf.Value);
            tb.CssClass = "searcxBoxNameInside valid";
            hf = (HiddenField)e.Row.FindControl("hfPosition");
            //btn.Attributes.Add("position", hf.Value);
            TextBox tbOrd = (TextBox)e.Row.FindControl("tborder1");
            HiddenField hford = (HiddenField)e.Row.FindControl("hfOrder");
            tbOrd.Text = hford.Value;
            if (hf.Value == "True")
            {
                ((RadioButtonList)e.Row.FindControl("rbPosition")).Items[0].Selected = true;
            }
            else
            {
                ((RadioButtonList)e.Row.FindControl("rbPosition")).Items[1].Selected = true;
            }
        }
    }
    protected void gvBanners_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        
    }
    protected void gvBanners_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        action = (e.CommandArgument == "update") ? Action.UPDATE : Action.DELETE;
    }
    protected void gvBanners_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        switch (action)
        {
            case Action.UPDATE:
                UpdateBanner(e);
                break;
            case Action.DELETE:
                DeleteBanner(e);
                break;
            default: break;
        }
        Response.Redirect(Request.Url.ToString());
    }

    private void DeleteBanner(GridViewDeleteEventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_DeleteBanner", conn))
            {
                GridViewRow r = gvBanners.Rows[e.RowIndex];
                HiddenField hf = (HiddenField)r.FindControl("hfId");
                SqlParameter[] pars = new SqlParameter[1];
                pars[0] = new SqlParameter("id", hf.Value);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                int val = 0;
                try
                {
                    val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    if (val > 0)
                    {
                        //delete the file
                        HiddenField hf_fname = (HiddenField)r.FindControl("hfFilename");
                        string str_file = Server.MapPath("../images/banners/") + hf.Value + "_" + hf_fname.Value;
                        if (File.Exists(str_file))
                        {
                            try
                            {
                                File.Delete(str_file);
                            }
                            catch (Exception ex) { }
                        }
                        Session["message"] = " Delete was succesfull<br />";
                        Session["message_type_css"] = "par_message_ok";
                    }
                }
                catch (Exception ex)
                {
                    Session["message"] = ex.ToString();
                    Session["message_type_css"] = "par_message_ok";
                }
            }
        }
    }

    private void UpdateBanner(GridViewDeleteEventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SP_UpdateBanners", conn))
            {
                GridViewRow r = gvBanners.Rows[e.RowIndex];
                HiddenField hf = (HiddenField)r.FindControl("hfId");
                SqlParameter[] pars = new SqlParameter[6];
                RadioButtonList rlist = (RadioButtonList)gvBanners.Rows[e.RowIndex].Cells[3].Controls[1];
                pars[0] = new SqlParameter("id", hf.Value);
                CheckBox cb = (CheckBox)gvBanners.Rows[e.RowIndex].Cells[2].Controls[0];
                TextBox tblink = (TextBox)gvBanners.Rows[e.RowIndex].Cells[1].Controls[3];
                hf = (HiddenField)r.FindControl("hfFilename");
                pars[1] = new SqlParameter("link", tblink.Text);
                hf = (HiddenField)r.FindControl("hfPosition");
                TextBox tbOrd = (TextBox)r.FindControl("tborder1");
                pars[2] = new SqlParameter("position", rlist.Items[0].Selected);
                pars[3] = new SqlParameter("filename", "");
                pars[4] = new SqlParameter("isActive", cb.Checked);
                int ord;
                if (!Int32.TryParse(tbOrd.Text, out ord))
                {
                    Session["message"] = "Order must be numeric";
                    Session["message_type_css"] = "par_message_error";
                    Response.Redirect(Request.Url.ToString());
                }
                if (tbOrd.Text != "")
                    pars[5] = new SqlParameter("order", tbOrd.Text);
                else pars[5] = new SqlParameter("order", 1);

                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                foreach (SqlParameter s in pars)
                    cmd.Parameters.Add(s);
                try
                {
                    int val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    if (val > 0)
                    {
                        Session["message"] = " Changes made succesfully<br />";
                        Session["message_type_css"] = "par_message_ok";
                    }
                }
                catch (Exception ex)
                {
                    Session["message"] = ex.ToString();
                    Session["message_type_css"] = "par_message_ok";
                }
            }
        }
    }
}
